//
//  SQLiteManager.swift
//  0226-FMDB演练
//
//  Created by 孙明海 on 16/2/26.
//  Copyright © 2016年 孙明海. All rights reserved.
//

import Foundation

/// 数据库名称
private let dbName = "my.db"

/// 数据库
class SQLiteManager {
     /// 单例
    static let sharedManager = SQLiteManager()
    
    let queue: FMDatabaseQueue
    
    private init() {
        var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        path = (path as NSString).stringByAppendingPathComponent(dbName)
        
        print(path)
        // 打开数据库
        queue = FMDatabaseQueue(path: path)
        
        /// 创建数据表
        createTable()
    }
    
    func execRecordSet(sql: String) -> [[String: AnyObject]] {
        var array = [[String: AnyObject]]()
        
        SQLiteManager.sharedManager.queue.inDatabase { (db) -> Void in
            guard let results = db.executeQuery(sql) else {
                print("没有查找到数据")
                return
            }
            
            while results.next() {
                let cols = results.columnCount()
                var dict = [String: AnyObject]()
                
                for col in 0..<cols {
                    let name = results.columnNameForIndex(col)
                    let obj = results.objectForColumnIndex(col)
                    
                    dict[name] = obj
                }
                array.append(dict)
            }
        }
        return array
    }
    
    /// 创建数据表
    private func createTable() {
        let path = NSBundle.mainBundle().pathForResource("db.sql", ofType: nil)!
        let sql = try! String(contentsOfFile: path)
        
        queue.inDatabase { (db) -> Void in
            if db.executeStatements(sql) {
                print("创建成功")
            } else {
                print("创建失败")
            }
        }
    }
}